package com.xiaoze.transform;

import com.xiaoze.entity.SensorReading;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * TransformReduce
 *
 * @author Lin Zemin
 * @date 2021-12-29
 */
public class TransformReduce {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\sensor.txt";
        DataStreamSource<String> inputStream = env.readTextFile(path);

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });

        // 分组
        KeyedStream<SensorReading, String> keyedStream = dataStream.keyBy(SensorReading::getId);

        // reduce聚合，取最大的温度值，当前最新的时间戳
        SingleOutputStreamOperator<SensorReading> reduce = keyedStream.reduce((ReduceFunction<SensorReading>) (sensorReading, t1) -> new SensorReading(sensorReading.getId(), t1.getTimeNum(), Math.max(sensorReading.getTemperature(), t1.getTemperature())));

        reduce.print();
        env.execute();

    }

}
